package net.dgg.dggcloud.service.jrcrm.aspect;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.entity.OperationRight;
import net.dgg.dggcloud.service.entity.Role;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.constant.SysRecordConstant;
import net.dgg.dggcloud.service.jrcrm.constant.OpreateEnum;
import net.dgg.dggcloud.service.jrcrm.constant.OpreateTypeEnum;
import net.dgg.dggcloud.service.jrcrm.service.log.SysModifyAuthRecordService;
import net.dgg.dggcloud.service.jrcrm.utils.IpUtil;
import net.dgg.dggcloud.service.service.OperationRightService;
import net.dgg.dggcloud.service.service.RoleService;
import net.dgg.framework.tac.mq.rabbitmq.queue.DggMessageSendUtil;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;

/**
 * 添加角色aop
 * 
 * @Title: RoleAuthOptSaveAspect
 * @Description:
 * @Auther: 雷力
 * @Date: 2018-11-23 09:48:35
 *
 */
@Aspect
@Component
public class RoleAuthOptSaveAspect {
	private Logger logger = Logger.getLogger(RoleAuthOptSaveAspect.class);

	@Autowired
	private RoleService roleService;
	@Autowired
	private OperationRightService operationRightService;

	@Pointcut("execution(public * net.dgg.dggcloud.platform.action.RoleController.authOptSave(..))")
	public void webLog() {
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Before("webLog()")
	public void before(JoinPoint jp) {
		try {
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = attributes.getRequest();
			User user = SessionManager.getCurrentUser();
			Object[] objs = jp.getArgs();
			Long roleId = Long.valueOf(objs[2].toString());
			Role role = roleService.find4Id(roleId);

			Map record = new HashMap<>();
			record.put("ip", IpUtil.getIPAddress(request));
			record.put("opreate", OpreateEnum.ROLEPERMISSION.getOpreate());
			record.put("opreateTime", DateUtil.dateToString(new Date()));
			record.put("userLoginname", user.getLoginName());
			record.put("userName", user.getName());
			record.put("vuserLoginname", role.getRoleKey());
			record.put("vuserName", role.getName());

			List<Long> olds = new ArrayList<>();

			Iterator<Map> imap = roleService.findOperationIdsByRoleId(roleId).iterator();
			while (imap.hasNext()) {
				Map map = imap.next();
				olds.add(Long.valueOf(map.get("operationid").toString()));
			}
			Long[] longs = objs[1] == null ? new Long[0] : (Long[]) objs[1];
			List<Long> news = new ArrayList<>(Arrays.asList(longs));
			List<Long> temps = new ArrayList<>();
			temps.addAll(olds);
			olds.removeAll(news);
			news.removeAll(temps);

			if (!olds.isEmpty()) {// 删除
				String strolds = StringUtils.join(olds, ",");
				List<OperationRight> menus = operationRightService.findCodeAndName4Ids(strolds);
				record.put("id", DggKeyWorker.nextId());
				record.put("opreateType", OpreateTypeEnum.DELETE.getType());
				StringBuffer sb = new StringBuffer();
				sb.append("{");
				Iterator<OperationRight> iterator = menus.iterator();
				while (iterator.hasNext()) {
					OperationRight or = iterator.next();
					sb.append(or.getOperationKey() + ":" + or.getName() + ",");
				}
				sb.deleteCharAt(sb.length() - 1);
				sb.append("}");
				record.put("modifyContent", sb.toString());
				record.put("clazz", SysModifyAuthRecordService.class);
				logger.info("======================>发送消息...");
				DggMessageSendUtil.putMessage(SysRecordConstant.QUEUENAME, record);
			}
			if (!news.isEmpty()) {// 添加
				String strnews = StringUtils.join(news, ",");
				List<OperationRight> operationRights = operationRightService.findCodeAndName4Ids(strnews);
				record.put("id", DggKeyWorker.nextId());
				record.put("opreateType", OpreateTypeEnum.ADD.getType());
				StringBuffer sb = new StringBuffer();
				sb.append("{");
				Iterator<OperationRight> iterator = operationRights.iterator();
				while (iterator.hasNext()) {
					OperationRight or = iterator.next();
					sb.append(or.getOperationKey() + ":" + or.getName() + ",");
				}
				sb.deleteCharAt(sb.length() - 1);
				sb.append("}");
				record.put("modifyContent", sb.toString());
				record.put("clazz", SysModifyAuthRecordService.class);
				logger.info("======================>发送消息...");
				DggMessageSendUtil.putMessage(SysRecordConstant.QUEUENAME, record);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
